import SparkMD5 from "spark-md5";

const loadNextChunk = (
  file: File,
  currentChunk: number,
  chunkSize: number,
  fileReader: any
) => {
  const start = currentChunk * chunkSize;
  const end = Math.min(start + chunkSize, file.size);
  fileReader.readAsArrayBuffer(file.slice(start, end));
};

export const calculateMD5: (file: File) => Promise<string> = (file) => {
  return new Promise((resolve) => {
    const chunkSize = 20 * 1024; // 20KB chunks
    const spark = new SparkMD5.ArrayBuffer();
    const fileReader = new FileReader();
    let currentChunk = 0;
    const chunks = Math.ceil(file.size / chunkSize);

    fileReader.onload = function (e) {
      spark.append(e.target?.result as ArrayBuffer);
      currentChunk++;
      if (currentChunk < chunks) {
        loadNextChunk(file, currentChunk, chunkSize, fileReader);
      } else {
        resolve(spark.end());
      }
    };

    loadNextChunk(file, currentChunk, chunkSize, fileReader);
  });
};
